<?php

namespace App\Admin\Controllers;

use Dcat\Admin\Layout\Content;
use App\Admin\Metrics\Orders;
use App\Admin\Repositories\Order;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class OrderDeductedController extends AdminController
{
    public function index(Content $content)
    {
        return $content
            ->header('扣量订单')
            ->body(function ($row) {
                $row->column(4, new Orders\DayOrderNumCount(['deduct'=>1]));
                $row->column(4, new Orders\DayOrderMoneyCount(['deduct'=>1]));
            })
            ->body($this->grid());
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Order(), function (Grid $grid) {
            $grid->model()->with('agent')->where('is_deduct',1)->orderBy('created_at','desc');
            $grid->column('id')->sortable();
            $grid->column('agent_id','代理 ID')->filter();
            $grid->column('agent.username','代理');
            $grid->column('video_id','视频ID');
            $grid->column('no','订单号');
            $grid->column('transaction_id');
            $grid->column('price','价格')->sortable();
            $grid->column('paid_at','支付时间')->sortable()->display(function($paid_at){
                if(!boolval($paid_at)){
                    return "<span style='color:gray'>未支付</span>";
                }
                return "<span style='color:green'>$paid_at</span>";
            });
            $grid->column('ip')->filter();
            // $grid->column('appid')->filter();
            $grid->column('mch_id','商户号')->filter();
            $grid->column('valid','是否有效')->sortable()->using([1 => '有效', 0 => '无效'])->label([
                'default' => 'primary', // 设置默认颜色，不设置则默认为 default
                0 => 'danger',
                1 => 'success',
            ]);
        
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->quickSearch(['no', 'video_id','agent_id','ip','transaction_id']);
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('no')->width(3);
                $filter->like('agent_id')->width(2);
                // 设置time类型
                $filter->between('paid_at')->datetime()->width(4);
            });

            $grid->header(function ($collection) use ($grid) {
                // foreach($collection as);
                $query = \App\Models\Order::query();
                // 拿到表格筛选 where 条件数组进行遍历
                $grid->model()->getQueries()->unique()->each(function ($value) use (&$query) {
                    // var_dump($value);
                    if (in_array($value['method'], ['paginate', 'get', 'orderBy', 'orderByDesc'], true)) {
                        return;
                    }
            
                    $query = call_user_func_array([$query, $value['method']], $value['arguments'] ?? []);
                });
                // 查出统计数据
                $data = $query->whereNotNull('paid_at')->sum('price');
            
                return "<div style='padding-bottom: 10px;padding-left: 1.8rem;font-weight:bold;color:red;background:#fff;'>当前查询扣量总金额 ：￥ $data</div>";
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Order(), function (Show $show) {
            $show->field('id');
            $show->field('agent_id');
            $show->field('openid');
            $show->field('video_id');
            $show->field('no');
            $show->field('transaction_id');
            $show->field('price');
            $show->field('paid_at');
            $show->field('appid');
            $show->field('mch_id');
            $show->field('valid');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Order(), function (Form $form) {
            $form->display('id');
            $form->text('agent_id');
            $form->text('openid');
            $form->text('video_id');
            $form->text('no');
            $form->text('transaction_id');
            $form->text('price');
            $form->text('paid_at');
            $form->text('appid');
            $form->text('mch_id');
            $form->text('valid');
        
            $form->display('created_at');
            $form->display('updated_at');

            $form->deleted(function (Form $form, $result) {
                // 获取待删除行数据，这里获取的是一个二维数组
                $data = $form->model()->toArray();
                foreach($data as $item){
                    cache()->forget("paid:{$item['openid']}:{$item['video_id']}");
                    cache()->forget("paid_ip:{$item['ip']}:{$item['video_id']}");
                }
            });
        });
    }
}
